import { Button, List, WhiteSpace, WingBlank, Badge, Checkbox, Icon, Toast } from 'antd-mobile';
import React, { Component } from 'react';
import { View, StyleSheet, ScrollView, Image, FlatList, Text } from 'react-native';
import { NavigationActions } from 'react-navigation'
import { Urls } from '../../utils/Urls';

const Item = List.Item;
const CheckboxItem = Checkbox.CheckboxItem;
const resetAction = NavigationActions.reset({
    index: 0,
    actions: [
        NavigationActions.navigate({ routeName: 'MainScreenNavigator', params: { token: '123456' } })
    ]
})

const loginAction = NavigationActions.reset({
    index: 0,
    actions: [
        NavigationActions.navigate({ routeName: 'LoginScreen', params: { token: '123456' } })
    ]
})

export class ChooseStationScreen extends Component {
    static navigationOptions = ({ navigation }) => ({
        headerTitle: navigation.state.params.title,
        headerTitleStyle: { alignSelf: 'center' }
    });
    state = {
        stationList: []
    }
    componentWillMount() {
        let url = Urls.BIND_STATION_LIST + "?size=1000";
        fetch(url)
            .then((response) => {
                console.log(response)
                var responsejson = JSON.parse(response._bodyInit);
                if (responsejson.code == 0) {
                    this.setState({
                        stationList: responsejson.content.list
                    })
                }  else  if (responsejson.code == 1) {
                    Toast.fail('登录过期，重新登录', 1);
                    this.props.navigation.dispatch(loginAction)
                }
            })
            .catch((error) => {
                console.log(error);
            })
    }
    
    onChange = (e, index) => {
        console.log(e, index);
        if (e.target.checked) {
            this.state.stationList[index].status = 2
        } else {
            this.state.stationList[index].status = 1
        }
    }
    submitStationIds = () => {
        let stationsIdList = [];

        let stationIds = '';
        this.state.stationList.map(i => {
            if (i.status == 2) {
                stationIds += `stations=${i.id}&`;
                stationsIdList.push(i.id)
            }
        })
        if (stationsIdList.length<=0) {
            Toast.fail("请勾选关注的变电站", 1);
            return false;
        }

        var opts = {
            method: "POST",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: stationIds
        }

        let url = Urls.bindStations;
        fetch(url, opts)
            .then(response => response.json())
            .then(data => {
                console.log(data);
                if (data.code == 0) { // 修改成功
                    Toast.success('关注成功', 1);
                    this.props.navigation.dispatch(resetAction)
                    JPushModule.setTags(stationsIdList, success => {
                        console.log("设置标签: ", success);
                        return false;
                    })
                } else { // 修改失败
                    Toast.fail('关注失败，请检查操作', 1);
                }
            })
    }
    render() {
        const { navigate } = this.props.navigation;
        return (
            <ScrollView>
                <WhiteSpace />
                <FlatList
                    data={this.state.stationList}
                    renderItem={({ item, index }) => <Item key={index}
                    // extra={item.equipments + '个探头'}
                    // arrow="horizontal"
                    // onClick={() => navigate('DeviceListScreen', { id: item.id })}
                    >
                        <CheckboxItem key={index} defaultChecked={item.status == 2} onChange={e => this.onChange(e, index)}>
                            <Text>{item.name} </Text>
                            {/* <Badge dot>
                            </Badge> */}
                        </CheckboxItem>
                        {/* <Text>{item.name} </Text> */}
                    </Item>}
                    onEndReached={this._onEndReached}
                    keyExtractor={(item, index) => index}
                />
                <Button
                    type="primary" inline size="large"
                    // onClick={() => navigate('MainScreenNavigator', { username: this.state.username,password: this.state.passwd })}
                    onClick={this.submitStationIds}
                >确定</Button>
            </ScrollView>
        );
    }
    _onEndReached = () => {
        // this.setState((state) => ({
        //   data: state.data.concat(genItemData(100, state.data.length)),
        // }));
        console.log("到底部了")
    };
}

const styles = StyleSheet.create({
    contentContainer: {
        padding: 10
    }
});
